import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.DbColumnType;
import com.baomidou.mybatisplus.generator.config.rules.DbType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  代码生成
 * </p>
 *
 * @author duaichao
 * @since 2018-08-23
 */
public class MysqlGenerator {
    /**
     * 包名
     */
    private static final String PACKAGE_NAME = "com.ssb.admin.modules";
    /**
     * 基础Controller
     */
    private static final String SUPER_CONTROLLER = "com.ssb.admin.common.controller.AbstractController";
    /**
     * 模块名称
     */
    private static final String BASE_MODULE = "sys";
    private static final String MODULE_NAME = "permission";
    private static final String[] TABLE_NAMES = new String[] {"sys_permission","sys_role_permission"};
    /**
     * 输出文件的路径
     */
    private static final String OUT_PATH = "D:\\ssbwork\\codeGen";
    private static final String RESOURCE_PATH = "D:\\ssbwork\\codeGen\\resources\\mapper\\";
    /**
     * 代码生成者
     */
    private static final String AUTHOR = "duaichao";

    /**
     * JDBC相关配置
     */
    private static final String DRIVER = "com.mysql.jdbc.Driver";
    private static final String URL = "jdbc:mysql://127.0.0.1:3306/springboot?useUnicode=true&characterEncoding=UTF-8";
    private static final String USER_NAME = "root";
    private static final String PASSWORD = "123456";

    public static void main(String[] args) {
        //user -> UserService, 设置成true: user -> IUserService
        boolean serviceNameStartWithI = true;
        generateByTables(serviceNameStartWithI, PACKAGE_NAME+"."+BASE_MODULE+"."+MODULE_NAME, TABLE_NAMES);
    }

    private static void generateByTables(boolean serviceNameStartWithI, String packageName, String... tableNames) {
        GlobalConfig config = new GlobalConfig();
        DataSourceConfig dataSourceConfig = new DataSourceConfig();
        dataSourceConfig.setDbType(DbType.MYSQL).setTypeConvert(new MySqlTypeConvert() {
            // 自定义数据库表字段类型转换【可选】
            @Override
            public DbColumnType processTypeConvert(String fieldType) {
                System.out.println("转换类型：" + fieldType);
                // if ( fieldType.toLowerCase().contains( "tinyint" ) ) {
                // return DbColumnType.BOOLEAN;
                // }
                return super.processTypeConvert(fieldType);
            }
        })
                .setUrl(URL)
                .setUsername(USER_NAME)
                .setPassword(PASSWORD)
                .setDriverName(DRIVER);
        StrategyConfig strategyConfig = new StrategyConfig();
        // strategy.setInclude(new String[] { "user" }); // 需要生成的表
        // strategy.setExclude(new String[]{"test"}); // 排除生成的表

        strategyConfig
                .setCapitalMode(true)
                .setEntityLombokModel(true)
                .setDbColumnUnderline(true)
                .setNaming(NamingStrategy.underline_to_camel)
                .setInclude(tableNames)
                .setSuperControllerClass(SUPER_CONTROLLER)
                .setRestControllerStyle(true)
                .setControllerMappingHyphenStyle(true);
        config.setActiveRecord(false)
                .setEnableCache(false)
                .setAuthor(AUTHOR)
                .setOutputDir(OUT_PATH)
                .setFileOverride(true)
                .setMapperName("%sDao")
                .setXmlName("%sDao");
        if (!serviceNameStartWithI) {
            config.setServiceName("%sService");
        }
        // 调整 xml 生成目录
        InjectionConfig injectionConfig = new InjectionConfig() {
            @Override
            public void initMap() {
            }
        };
        List list = new ArrayList();
        list.add(new FileOutConfig("/templates/mapper.xml.vm") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 生成文件的输出目录
                return RESOURCE_PATH +"\\"+BASE_MODULE+"\\"+ tableInfo.getEntityName() + "Mapper.xml";
            }
        });
        injectionConfig.setFileOutConfigList(list);
        // 关闭默认 xml 生成，调整生成 至 根目录
        TemplateConfig templateConfig = new TemplateConfig();
        // 去掉自定义模板
        templateConfig.setXml(null);

        new AutoGenerator().setGlobalConfig(config)
                .setDataSource(dataSourceConfig)
                .setStrategy(strategyConfig)

                .setPackageInfo(
                        new PackageConfig()
                                .setParent(packageName)
                                .setMapper("dao")
                                .setController("controller")
                                .setEntity("entity")
                )
                .setCfg(injectionConfig)
                .setTemplate(templateConfig)
                .execute();
    }


}
